const FileDownloader = require('./fileDownloader');
const QueueManager = require('./queueManager');
const { TaskStatus } = require('../models/task');

/**
 * 下载服务
 * 协调文件下载器和队列管理器，提供完整的下载服务
 */
class DownloadService {
  constructor(downloadDirectory = null, cookie = null) {
    this.fileDownloader = new FileDownloader(downloadDirectory, cookie);
    this.queueManager = new QueueManager();
    this.isProcessing = false;
    this.processingInterval = null;

    // 启动时检查是否有未完成的任务
    this.recoverPendingTasks();

    // 启动队列处理
    this.startProcessing();
  }

  /**
   * 恢复未完成的任务
   */
  recoverPendingTasks() {
    const downloadingTasks = this.queueManager.getTasksByStatus(TaskStatus.DOWNLOADING);

    // 将正在下载的任务重置为待处理
    for (const task of downloadingTasks) {
      console.log(`🔄 恢复任务状态: ${task.id} -> ${TaskStatus.PENDING}`);
      this.queueManager.updateTask(task.id, TaskStatus.PENDING);
    }

    // 清除当前任务状态
    this.queueManager.clearCurrentTask();
  }

  /**
   * 启动队列处理
   */
  startProcessing() {
    if (this.processingInterval) {
      return;
    }

    console.log('🚀 启动下载队列处理器');

    // 立即处理一次
    this.processQueue();

    // 每5秒检查一次队列
    this.processingInterval = setInterval(() => {
      this.processQueue();
    }, 5000);
  }

  /**
   * 停止队列处理
   */
  stopProcessing() {
    if (this.processingInterval) {
      clearInterval(this.processingInterval);
      this.processingInterval = null;
      console.log('⏹️  停止下载队列处理器');
    }
  }

  /**
   * 处理队列
   */
  async processQueue() {
    if (this.isProcessing) {
      return;
    }

    const nextTask = this.queueManager.getNextTask();
    if (!nextTask) {
      return;
    }

    this.isProcessing = true;
    this.queueManager.setCurrentTask(nextTask.id);

    try {
      console.log(`📥 开始处理任务: ${nextTask.id} - ${nextTask.url}`);

      // 更新任务状态为下载中
      this.queueManager.updateTask(nextTask.id, TaskStatus.DOWNLOADING, {
        startedAt: new Date()
      });

      // 设置回调函数
      const callbacks = {
        onStart: (fileName, fileSize) => {
          console.log(`📄 开始下载: ${fileName} (${this.fileDownloader.formatFileSize(fileSize)})`);
          this.queueManager.updateTask(nextTask.id, TaskStatus.DOWNLOADING, {
            fileName,
            fileSize
          });
        },

        onProgress: (downloadedSize, totalSize, progress) => {
          this.queueManager.updateTaskProgress(nextTask.id, downloadedSize, totalSize, progress);
        },

        onComplete: (result) => {
          console.log(`✅ 任务完成: ${nextTask.id} - ${result.fileName}`);
          this.queueManager.updateTask(nextTask.id, TaskStatus.COMPLETED, {
            fileName: result.fileName,
            filePath: result.filePath,
            fileSize: result.fileSize,
            downloadedSize: result.fileSize,
            progress: 100,
            completedAt: new Date()
          });
        },

        onError: (error) => {
          console.error(`❌ 任务失败: ${nextTask.id} - ${error.message}`);
          this.queueManager.updateTask(nextTask.id, TaskStatus.FAILED, {
            error: error.message,
            completedAt: new Date()
          });
        }
      };

      // 执行下载
      await this.fileDownloader.downloadFile(
        nextTask.url,
        nextTask.customFileName,
        callbacks
      );

    } catch (error) {
      console.error(`❌ 处理任务异常: ${nextTask.id} - ${error.message}`);
      this.queueManager.updateTask(nextTask.id, TaskStatus.FAILED, {
        error: error.message,
        completedAt: new Date()
      });
    } finally {
      this.queueManager.clearCurrentTask();
      this.isProcessing = false;
    }
  }

  /**
   * 添加下载任务
   * @param {string} url - 下载链接
   * @param {string} customFileName - 自定义文件名（可选）
   * @returns {Object} 任务信息
   */
  addDownloadTask(url, customFileName = null) {
    try {
      // 验证URL格式
      new URL(url);

      const task = this.queueManager.addTask(url, customFileName);

      console.log(`➕ 添加下载任务: ${task.id}`);
      console.log(`   URL: ${url}`);
      if (customFileName) {
        console.log(`   自定义文件名: ${customFileName}`);
      }

      return {
        success: true,
        task: task.getSummary(),
        message: '任务已添加到队列'
      };
    } catch (error) {
      console.error(`❌ 添加任务失败: ${error.message}`);
      throw error;
    }
  }

  /**
   * 获取任务状态
   * @param {string} taskId - 任务ID
   * @returns {Object} 任务详情
   */
  getTaskStatus(taskId) {
    const task = this.queueManager.getTask(taskId);
    if (!task) {
      throw new Error('任务不存在');
    }

    return {
      success: true,
      task: task.getDetails()
    };
  }

  /**
   * 获取队列状态
   * @returns {Object} 队列信息
   */
  getQueueStatus() {
    const summary = this.queueManager.getQueueSummary();
    const allTasks = this.queueManager.getAllTasks()
      .map(task => task.getSummary())
      .sort((a, b) => new Date(a.addedAt) - new Date(b.addedAt));

    return {
      success: true,
      queue: {
        ...summary,
        tasks: allTasks
      }
    };
  }

  /**
   * 获取下载历史
   * @param {number} limit - 限制数量
   * @param {string} status - 过滤状态（可选）
   * @returns {Object} 历史记录
   */
  getDownloadHistory(limit = 50, status = null) {
    let tasks = this.queueManager.getAllTasks();

    // 状态过滤
    if (status) {
      tasks = tasks.filter(task => task.status === status);
    }

    // 排序（最新的在前）
    tasks.sort((a, b) => new Date(b.addedAt) - new Date(a.addedAt));

    // 限制数量
    if (limit > 0) {
      tasks = tasks.slice(0, limit);
    }

    return {
      success: true,
      history: {
        total: tasks.length,
        tasks: tasks.map(task => task.getSummary())
      }
    };
  }

  /**
   * 删除任务
   * @param {string} taskId - 任务ID
   * @returns {Object} 操作结果
   */
  deleteTask(taskId) {
    try {
      const success = this.queueManager.removeTask(taskId);
      if (!success) {
        throw new Error('任务不存在');
      }

      return {
        success: true,
        message: '任务已删除'
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 取消任务
   * @param {string} taskId - 任务ID
   * @returns {Object} 操作结果
   */
  cancelTask(taskId) {
    try {
      const success = this.queueManager.cancelTask(taskId);
      if (!success) {
        throw new Error('任务不存在');
      }

      return {
        success: true,
        message: '任务已取消'
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 重试任务
   * @param {string} taskId - 任务ID
   * @returns {Object} 操作结果
   */
  retryTask(taskId) {
    try {
      const success = this.queueManager.retryTask(taskId);
      if (!success) {
        throw new Error('任务不存在');
      }

      return {
        success: true,
        message: '任务已重新加入队列'
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 清理历史任务
   * @param {number} maxAge - 最大保留天数
   * @returns {Object} 清理结果
   */
  cleanupHistory(maxAge = 7) {
    const cleaned = this.queueManager.cleanupCompletedTasks(maxAge);

    return {
      success: true,
      cleaned,
      message: `清理了 ${cleaned} 个过期任务`
    };
  }

  /**
   * 获取服务统计信息
   * @returns {Object} 统计信息
   */
  getServiceStats() {
    const stats = this.queueManager.getStats();
    const summary = this.queueManager.getQueueSummary();

    return {
      success: true,
      stats: {
        ...stats,
        isProcessing: this.isProcessing,
        processingEnabled: !!this.processingInterval,
        currentTask: summary.currentTask,
        uptime: process.uptime(),
        memoryUsage: process.memoryUsage()
      }
    };
  }

  /**
   * 销毁服务
   */
  destroy() {
    this.stopProcessing();
    console.log('🛑 下载服务已停止');
  }
}

module.exports = DownloadService;
